﻿#include "logger.h"

#include <QDate>
#include <QDir>
#include <QDebug>
#include <QCoreApplication>

std::unique_ptr<g3::LogWorker> worker;

Logger::Logger(std::string appName,std::string id):m_sLogFolder(QCoreApplication::applicationDirPath() + "/log/")
{
    deleteOldLog(7);

    QDir tempDir;
    if (!tempDir.exists(m_sLogFolder))
        tempDir.mkpath(m_sLogFolder);

//    worker = g3::LogWorker::createLogWorker();
//    auto handle = worker->addDefaultLogger(appName, m_sLogFolder.toStdString(),id);
//    g3::initializeLogging(worker.get());
//    handle->call(&g3::FileSink::overrideLogDetails, &g3::LogMessage::FullLogDetailsToString);

    // scope to exit the logger
    std::string rotateFileLog = appName + "_" + QDateTime::currentDateTime().toString("yyyy_MM_dd_hh_mm_ss").toStdString();
    std::string directory = m_sLogFolder.toStdString();

    using namespace g3;
    worker = g3::LogWorker::createLogWorker();
    g3::initializeLogging(worker.get());

    // ------------ RotateSink
    const int k100MBInBytes = 100 * 1024 * 1024;
//    const int k100MBInBytes = 10 * 1024;
    //std::make_unique<LogRotate>(rotateFileLog, directory)是C++14的语法
//    auto rotateSinkHandle = worker->addSink(std::make_unique<LogRotate>(rotateFileLog, directory),
//                            &LogRotate::save);
   //C++11的语法
    auto rotateSinkHandle = worker->addSink(std::unique_ptr<LogRotate>(new LogRotate(rotateFileLog, directory)),
                            &LogRotate::save);
    // change the max file size so we hit it easily
    rotateSinkHandle->call(&LogRotate::setMaxLogSize, k100MBInBytes).wait();
}

Logger::~Logger()
{
    g3::internal::shutDownLogging();
}

void Logger::deleteOldLog(int days)
{
    const QDate today = QDate::currentDate();

    Q_FOREACH(auto  fileInfo, QDir(m_sLogFolder).entryInfoList())
    {
        if (fileInfo.birthTime().date().daysTo(today)>days)
        {
            QString filepath = fileInfo.absoluteFilePath();
            QDir deletefile;
            deletefile.setPath(filepath);
            if (deletefile.remove(filepath)){
                qDebug() << "File " + filepath + " is deleted!";
            }
        }
    }

}
